// pages/detail/detail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    button_type:false
  },
   // 投票
  onGotUserInfo: function (e) {
    let that = this;
    if (app.globalData.opid) {
      wx.showLoading({
        title: '马上投票',
      })
      wx.request({
        url: app.globalData.url + 'voting.php?Action=toupiao',
        data: {
          openid: app.globalData.opid,
          id: e.currentTarget.dataset.id
        },
        success: function (res) {
          console.log(res)
          wx.hideLoading()
          if (res.data.success == 1) {
            wx.showToast({
              title: res.data.msg,
              duration: 1000,
              mask: true,
              icon: 'success',
            })

            // 统计
            wx.request({
              url: app.globalData.url + 'voting.php?Action=tongji',
              success: function (res) {
                console.log(res)
                that.setData({
                  tongji: res.data
                })
              }
            })
            wx.request({
              url: app.globalData.url + 'voting.php?Action=votelist',
              success: function (res) {
                console.log(res)
                that.setData({
                  votelist: res.data
                })
              }
            })

            setTimeout(function () {
              wx.showModal({
                title: '温馨提醒',
                content: '您获得一次抽奖机会，是否进行抽奖？',
                success(res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '../luck_draw/luck_draw',
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            }, 2000)
          } else {
            wx.showToast({
              title: res.data.msg,
              duration: 1000,
              mask: true,
              icon: 'none',
            })
          }

        }
      })
      return false
    }
    if (e.detail.userInfo) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      app.globalData.loginState = false
      that.setData({
        loginState: false
      })
      wx.request({
        url: app.globalData.url + 'wxlogin.php',
        data: {
          name:
            JSON.stringify({
              code: app.globalData.code,
              user: e.detail.userInfo,
              openid: app.globalData.shareopenid
            })
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (loginOk) {
          console.log(loginOk.data)
          wx.setStorageSync('opid', loginOk.data.openid)
          app.globalData.opid = loginOk.data.openid
          wx.hideLoading()
          if(loginOk.data.openid){
            that.setData({
              button_type:true
            })
            wx.request({
              url: app.globalData.url + 'voting.php?Action=toupiao',
              data: {
                openid: app.globalData.opid,
                id: e.currentTarget.dataset.id
              },
              success: function (res) {
                console.log(res)
                wx.hideLoading()
                if (res.data.success == 1) {
                  wx.showToast({
                    title: res.data.msg,
                    duration: 1000,
                    mask: true,
                    icon: 'success',
                  })

                  // 统计
                  wx.request({
                    url: app.globalData.url + 'voting.php?Action=tongji',
                    success: function (res) {
                      console.log(res)
                      that.setData({
                        tongji: res.data
                      })
                    }
                  })
                  wx.request({
                    url: app.globalData.url + 'voting.php?Action=votelist',
                    success: function (res) {
                      console.log(res)
                      that.setData({
                        votelist: res.data
                      })
                    }
                  })

                  setTimeout(function () {
                    wx.showModal({
                      title: '温馨提醒',
                      content: '您获得一次抽奖机会，是否进行抽奖？',
                      success(res) {
                        if (res.confirm) {
                          wx.navigateTo({
                            url: '../luck_draw/luck_draw',
                          })
                        } else if (res.cancel) {
                          console.log('用户点击取消')
                        }
                      }
                    })
                  }, 2000)
                } else {
                  wx.showToast({
                    title: res.data.msg,
                    duration: 1000,
                    mask: true,
                    icon: 'none',
                  })
                }

              }
            })
          }

        }
      })
    }
    else {
      wx.showModal({
        title: '用户信息授权失败，请重新授权',
        content: '为了更好的为你提供服务，我们申请获得你的公开用户信息（昵称，头像）',
        showCancel: false,
        confirmText: '去授权',
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting["scope.userInfo"]) {
                  app.globalData.loginState = false
                  app.globalData.loginFn(e.detail.userInfo)
                  wx.getSetting({
                    success(res) {
                      res.authSetting['scope.userInfo'] = false
                    }
                  })

                }
              }

            })
          }
        }
      })
    }
  },
  shengcheng:function(){
    var that =this;
    console.log(123)
    if(app.globalData.opid == ""){
      wx.showToast({
        title: '您还没授权，请授权再转发，点击《投TA一票》按钮授权',
        icon: "none",
        duration: 2500
      })
      return false
    }
    wx.showLoading({
      title: '海报生成中...',
    })
    that.setData({
      zhe: true,
      fenxiang: true

    })
    wx.request({
      url: app.globalData.url +'ziyu.php?Action=tpscerweima',
      data:{
        id: that.data.id
      },
      success:function(res){
        console.log(res)
        wx.downloadFile({
          url: res.data.erweima,
          success: function (res) {
            console.log(res.tempFilePath);
            var width = that.data.canvasWidth;
            var rem = width/750;
            console.log(width)
            console.log(rem)
            // const wxGetImageInfo = promisify(wx.getImageInfo)
            var context = wx.createCanvasContext('myCanvas');
            context.setFillStyle("#fff");
            context.fillRect(0, 0, 700 * rem, 1250*rem);
            
            // context.setFillStyle("#fff");
            // context.fillRect(90, 52, 160, 160);
            
            // var path2 = that.data.picPath;
            // context.drawImage(path2, 100, 62, 150, 150);
           
            var path = "./img/bg.png";
            //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
            //不知道是什么原因，手机环境能正常显示t
            context.drawImage(path, 0, 0, 700 * rem, 580*rem);

            context.setFillStyle("#fff");
            context.fillRect(190*rem,90*rem , 320 * rem, 320 * rem);

             var path2 = that.data.picPath;
            context.drawImage(path2, 200*rem, 100*rem, 300 * rem, 300 * rem);
            var name = that.data.detail.option_name;
           

            var name1 = "我已投票，支持"+that.data.detail.option_name;
            console.log(name1)
            context.setFontSize(32*rem)
            context.setFillStyle("#de0020");
            context.font = '#de0020';
            context.setTextAlign('center')
            context.fillText(name1, 350*rem, 620*rem);

            
            context.setFontSize(32*rem)
            context.setFillStyle("#333333");
            context.setTextAlign('left')
            context.fillText("参赛宣言：", 40*rem, 670*rem);


            var name3 = that.data.detail.option_content;

            context.setFontSize(28*rem)
            context.setFillStyle("#666");
            context.setTextAlign('left')
            // context.fillText(name3, 40*rem, 720*rem);
            that.drawText(context, name3, 40 * rem, 720 * rem, 148,(480*rem))

           

            context.setFontSize(36*rem)
            context.setFillStyle("#161616");
            context.setTextAlign('left')
            context.fillText("微信识别二维码", 360 * rem, 900 * rem);
            context.fillText("进入人气之星投票榜", 360 * rem, 960*rem);

            context.setFillStyle("#fff");
            context.setFontSize(40 * rem)
            // context.font = 'normal bold sans-serif';
            context.setTextAlign('center')
            context.fillText(name, 350 * rem, 470 * rem);


            var path1 = res.tempFilePath;
            console.log(path1)
            context.drawImage(path1, 40 * rem, 800 * rem, 240 * rem, 240 * rem);




            context.draw();
            setTimeout(function () {
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 700 * rem  ,
                height: 1250 * rem ,
                destWidth: 700 * rem*2,
                destHeight: 1250 * rem*2,
                canvasId: 'myCanvas',
                success: function (res) {
                  console.log(res.tempFilePath)

                  var arr = [];
                  arr.push(res.tempFilePath)
                  wx.previewImage({
                    current: "", // 当前显示图片的http链接
                    urls: arr, // 需要预览的图片http链接列表
                    success: function (res) {
                      wx.hideLoading()
                      wx.request({
                        url: app.globalData.url + 'voting.php?Action=ffshare',
                        data: {
                          openid: app.globalData.opid,
                          S_types: 3,
                          S_productid: that.data.id
                        },
                        success: function (res) {
                          console.log(res)
                        }
                      })
                      that.setData({
                        zhe: false,
                        fenxiang: false

                      })
                    }
                  })

                },
                fail: function (res) {
                  console.log(res)
                  wx.hideLoading()
                  wx.showToast({
                    title: '海报生成失败，请重试',
                    icon:"none"
                  })
                }
              })
            }, 1000);

          }, fail: function (fres) {

          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  panduan:function(){
    wx.showToast({
      title: '您还没授权，请授权再转发，点击《投TA一票》按钮授权',
      icon:"none",
      duration:2500
    })
  },
  onLoad: function (options) {
    var that = this;
    console.log(options)
    if(options.openid){
      console.log("有分享id")
      if(options.openid != app.globalData.opid){
        wx.request({
          url: app.globalData.url + 'voting.php?Action=ffshare',
          data: {
            openid: options.openid,
            S_types: 2,
            S_productid: options.id
          },
          success: function (res) {
            console.log("id不同，可以触发")
          }
        })
      }else{
        console.log('分享openID跟自己openID相同')
      }
    }
    if(!app.globalData.opid == "" ){
      that.setData({
        button_type:true
      })
    }
    wx.showLoading({
      title: '加载中',
    })
    console.log(options)
    
    wx.request({
      url: app.globalData.url +'voting.php?Action=votedetail',
      data:{
        id:options.id
      },
      success:function(res){
        wx.hideLoading()
        console.log(res)
        wx.setNavigationBarTitle({
          title: res.data.option_name,
          id: options.id
        })
        wx.downloadFile({
          url: res.data.option_pic,
          success: function (res) {
            that.setData({
              picPath: res.tempFilePath
            })
          }
        
        })
        that.setData({
          detail:res.data,
          id:options.id
        })
        
      }
    })
    var myCanvasWidth;
    var myCanvasHeight;
    
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        myCanvasWidth = res.windowWidth;
        myCanvasHeight = res.windowHeight;
      },
    })
    that.setData({
      canvasWidth: myCanvasWidth,
      canvasHeight: myCanvasHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('页面卸载时')
    wx.switchTab({
      url: '../index/index',
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    console.log("分享的openid:"+app.globalData.opid)
    return {
      title: '每日一票，100%中奖，精美的礼品等着你~~~' + that.data.detail.option_name,
      path: '/pages/zhuan/zhuan?id=' + that.data.id +"&openid="+app.globalData.opid
    }

  }
})